import React, { useCallback, useMemo } from 'react';
import Cabinet from './Cabinet';
import { CabinetData } from '../../../types';

/**
 * 机柜管理器组件 - 负责管理和渲染多个机柜
 * @param cabinets 机柜数据数组
 * @param selectedCabinetId 当前选中的机柜ID
 * @param onCabinetSelect 机柜选择回调函数
 */
interface CabinetManagerProps {
  cabinets: CabinetData[];
  selectedCabinetId?: string;
  onCabinetSelect?: (cabinetId: string) => void;
}

const CabinetManager: React.FC<CabinetManagerProps> = ({ cabinets, selectedCabinetId, onCabinetSelect }) => {
  // 处理机柜选择 - 使用useCallback缓存函数引用
  const handleCabinetSelect = useCallback((cabinetId: string) => {
    if (onCabinetSelect) {
      onCabinetSelect(cabinetId);
    }
  }, [onCabinetSelect]);

  // 检查机柜是否被选中 - 使用useCallback缓存函数引用
  const getCabinetIsSelected = useCallback((cabinetId: string) => {
    return cabinetId === selectedCabinetId;
  }, [selectedCabinetId]);

  // 使用useMemo缓存渲染的机柜列表，避免不必要的重渲染
  const renderedCabinets = useMemo(() => {
    return cabinets.map((cabinet) => (
      <Cabinet
        key={cabinet.id}
        cabinet={cabinet}
        isSelected={getCabinetIsSelected(cabinet.id)}
        onSelect={handleCabinetSelect}
      />
    ));
  }, [cabinets, getCabinetIsSelected, handleCabinetSelect]);

  return (
    <group>
      {renderedCabinets}
      
      {/* 可以在这里添加机柜组的公共效果，如选中框、信息面板等 */}
    </group>
  );
};

export default React.memo(CabinetManager);